﻿/*
Copyright (c) 2008 Martin Legris

Permission is hereby granted, free of charge, to any person obtaining a copy of this 
software and associated documentation files (the "Software"), to deal in the Software 
without restriction, including without limitation the rights to use, copy, modify, 
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to the following 
conditions:

The above copyright notice and this permission notice shall be included in all copies 
or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ignore
*/
package newcommerce.lastfm.api.clients 
{
	import com.gsolo.encryption.MD5;
	import flash.events.ErrorEvent;
	import newcommerce.lastws.AbstractClient;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import newcommerce.lastfm.api.data.LFMAlbumData;
	import newcommerce.lastfm.api.events.LFMScrobbleEvent;
	import newcommerce.lastfm.api.LastFMClient;
	import newcommerce.lastws.RequestWrapper;
	
	/**
	 * ...
	 * @author Martin Legris ( http://blog.martinlegris.com )
	 */
	public class ScrobbleClient extends AbstractClient
	{
		protected var _currentTrack:String;
		protected var _currentArtist:String;
		protected var _clientId:String = "tst";
		protected var _version:String = "1.2.1";
		protected var _sessionId:String;
		
		protected var _handshakeUrl:String = "http://post.audioscrobbler.com/";
		protected var _nowPlayingUrl:String = "";
		protected var _submissionUrl:String = "";
		
		public function ScrobbleClient() 
		{
			super();
		}
		
		public function handshake(username:String):Number
		{
			var url:String = _handshakeUrl;
			
			var variables:URLVariables = new URLVariables();
			variables.hs = "true";
			variables.p = _version;
			variables.c = _clientId;
			variables.v = "0.0.1";
			variables.u = username;
			variables.t = Math.floor((new Date().getTime()) / 1000);
			variables.api_key = LastFMClient.apiKey;
			variables.sk = LastFMClient.sessionKey;
			variables.a = MD5.encrypt(LastFMClient.secret + variables.t);
			
			var request:URLRequest = new URLRequest(url);
			request.data = variables;
			
			return runLoader(request, doHandshake, doHandshakeError, createWrapper({ username:username }) );
		}
		
		public function nowPlaying(artistName:String, trackName:String, trackNumber:Number = -1, albumName:String = "", trackLength:Number = -1, mbid:String = ""):Number
		{
			var url:String = _nowPlayingUrl;
			
			var variables:URLVariables = new URLVariables();
			variables.a = artistName;
			variables.t = trackName;
			variables.b = albumName;
			variables.m = mbid;
			variables.n = (trackNumber != -1)? trackNumber : "";
			variables.l = (trackLength != -1) ? trackLength : "";
			variables.s = _sessionId;
			
			var request:URLRequest = new URLRequest(url);
			request.data = variables;
			request.method = URLRequestMethod.POST;
			
			return runLoader(request, doNowPlaying, doNowPlayingError, createWrapper({ artist:artistName, track:trackName, album:albumName, length:trackLength, mbid:mbid, number:trackNumber } ));
		}
		
		public function submitOne(artistName:String, trackName:String, trackLength:Number, listenedAt:Date, source:String = "P", rating:String = "", albumName:String = "", trackNumber:Number = -1, mbid:String = ""):Number
		{
			var url:String = _submissionUrl;
			
			var variables:URLVariables = new URLVariables();
			variables.s = _sessionId;
			variables["a[0]"] = artistName;
			variables["t[0]"] = trackName;
			variables["i[0]"] = Math.floor(listenedAt.getTime() / 1000);
			variables["o[0]"] = source;
			variables["r[0]"] = rating;
			variables["l[0]"] = trackLength;
			variables["b[0]"] = albumName;
			variables["n[0]"] = trackNumber != -1 ? trackNumber : "";
			variables["m[0]"] = mbid;
			
			var request:URLRequest = new URLRequest(url);
			request.data = variables;
			request.method = URLRequestMethod.POST;
			
			return runLoader(request, doSubmittedOne, doSubmittedOneError, createWrapper( { artist:artistName, track:trackName, listenedAt:listenedAt, source:source, rating:rating, album:albumName, trackNumber:trackNumber, mbid:mbid }) );
		}
		
		protected function doSubmittedOne(evt:Event):void
		{
			var data:String = evt.target.data as String;
			var wrapper:RequestWrapper = getWrapper(evt.target as URLLoader);
			
			if (data.indexOf("OK") == 0)
			{
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.SUBMIT_ONE_SUCCESS, wrapper.requestId, wrapper));
			}
			else
			{
				wrapper.error = data;
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.SUBMIT_ONE_FAILURE, wrapper.requestId, wrapper));
			}
		}
		
		protected function doSubmittedOneError(evt:ErrorEvent, wrapper:RequestWrapper):void
		{
			dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.SUBMIT_ONE_FAILURE, wrapper.requestId, wrapper));
		}
		
		protected function doNowPlaying(evt:Event):void
		{
			var data:String = evt.target.data as String;
			var wrapper:RequestWrapper = getWrapper(evt.target as URLLoader);
			
			trace("now playing returned:" + data);
			
			if (data.indexOf("OK") == 0)
			{
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.NOW_PLAYING_SUCCESS, wrapper.requestId, wrapper));
			}
			else
			{
				wrapper.error = data;
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.NOW_PLAYING_FAILURE, wrapper.requestId, wrapper));
			}
		}
		
		protected function doNowPlayingError(evt:ErrorEvent, wrapper:RequestWrapper):void
		{
			dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.NOW_PLAYING_FAILURE, wrapper.requestId, wrapper));
		}
		
		protected function doHandshake(evt:Event):void
		{
			var data:String = evt.target.data;	
			var wrapper:RequestWrapper = getWrapper(evt.target as URLLoader);
			
			data = data.replace("\r\n", "\n");
			var lines:Array = data.split("\n");
			if (lines[0] == "OK")
			{
				_nowPlayingUrl = lines[2];
				_submissionUrl = lines[3];
				_sessionId = lines[1];
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.HANDSHAKE_SUCCESS, wrapper.requestId, wrapper));
			}
			else
			{
				dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.HANDSHAKE_FAILURE, wrapper.requestId, wrapper));
			}
		}
		
		protected function doHandshakeError(evt:ErrorEvent, wrapper:RequestWrapper):void
		{
			dispatchEvent(new LFMScrobbleEvent(LFMScrobbleEvent.HANDSHAKE_FAILURE, wrapper.requestId, wrapper));
		}
	}
}